package xps.and.uudaijia.userclient.view.base;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import nucleus.presenter.Presenter;
import nucleus.view.NucleusAppCompatActivity;
import xps.and.uudaijia.userclient.R;

public abstract class BaseActivity<P extends Presenter> extends NucleusAppCompatActivity<P> implements Handler.Callback, DialogInterface.OnDismissListener,
        ActivityCompat.OnRequestPermissionsResultCallback {
    protected AlertDialog loadingDialog;
    protected Realm realm;


    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.CALL_PHONE
    };

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;


    private static final int PERMISSON_REQUESTCODE = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = getLayout();
        if (layoutId != 0)
            setContentView(layoutId);

        View view = getLayoutInflater().inflate(R.layout.dialog_progress, null);
        AlertDialog.Builder ABuilder = new AlertDialog.Builder(BaseActivity.this, R.style.ProgreessDialog);
        loadingDialog = ABuilder.setView(view).setCancelable(false).create();
        loadingDialog.setOnDismissListener(this);

        try {
            realm = Realm.getDefaultInstance();
        } catch (IllegalStateException ill) {
            ill.printStackTrace();
        }

        init();
        setData();

    }

    //获取用户
//    protected User getUser() {
//        User user;
//        if (realm != null) {
//            user = realm.where(User.class).findFirst();
//            return user;
//        }
//
//        return null;
//    }
    public void photoUploadSuccess() {
    }

    public void showDialogNoCancel() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.setCancelable(false);
            loadingDialog.show();
        }
    }

    public void showDialog() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.setCancelable(true);
            loadingDialog.show();
        }
    }

    public void dissmisDialog() {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    protected abstract int getLayout();

    protected abstract void setData();

    protected abstract void init();

    protected void dialogDismiss() {
    }

    public Realm getmRealm() {
        return realm;
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    public void showHintDialog(String hintText, OnClickListener listener) {
        ViewHolder contentViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.dialog_hintview, null));
        View contentView = contentViewHolder.getInflatedView();
        ViewHolder footerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.dialog_footer, null));
        View footerView = footerViewHolder.getInflatedView();

        ((TextView) contentView.findViewById(R.id.tv_hint)).setText(hintText);
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(contentViewHolder)
                .setGravity(Gravity.CENTER)
                .setFooter(footerView)
                .setOnClickListener(listener)
                .setHeader(R.layout.dialog_header)
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .create();

        dialog.show();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        dialogDismiss();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
    }

    private void checkPermissions(String... permissions) {

        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED) {
                needRequestPermissonList.add(perm);
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        this, perm)) {
                    needRequestPermissonList.add(perm);
                }
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

}

